using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
public class FPSComponent : DrawableGameComponent
{
    private SpriteBatch spriteBatch;
    private SpriteFont videoFont;
    private float elapsedTime;
    private float totalFrames;
    private float fps;
    private string fontName;
    private Color textColor = Color.Red;

    public string FontName
    {
        get { return fontName; }
        set
        {
            if (string.IsNullOrEmpty(value))
                return;

            fontName = value;
            if (spriteBatch != null)
                videoFont = Game.Content.Load<SpriteFont>(fontName);
        }
    }

    public Color Color
    {
        get { return textColor; }
        set { textColor = value; }
    }


    public FPSComponent(Game game)
        : base(game)
    {
    }

    public FPSComponent(Game game, bool show)
        : base(game)
    {
        Visible = show;
    }

    public FPSComponent(Game game, string fontName)
        : base(game)
    {
        this.fontName = fontName;
    }

    public FPSComponent(Game game, string fontName, bool show)
        : base(game)
    {
        this.fontName = fontName;
        Visible = show;
    }

    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(Game.GraphicsDevice);

        // Load the font if fontName has been set.
        if (!string.IsNullOrEmpty(fontName))
            videoFont = Game.Content.Load<SpriteFont>("Fonts/" + fontName);
    }

    public override void Update(GameTime gameTime)
    {
        elapsedTime += (float)gameTime.ElapsedGameTime.TotalSeconds;
        totalFrames++;

        if (elapsedTime >= 1.0f)
        {
            fps = totalFrames;
            totalFrames = 0;
            elapsedTime = 0;
        }
    }

    public override void Draw(GameTime gameTime)
    {
        if (fontName.Length > 0)
        {
            spriteBatch.Begin();
            spriteBatch.DrawString(
                videoFont,
                "FPS=" + fps,
                new Vector2(videoFont.LineSpacing),
                textColor,
                0f,
                Vector2.Zero,
                1f,
                SpriteEffects.None,
                0);
            spriteBatch.End();
        }
    }
}